<?php

namespace App\Http\Controllers;

use App\Repositories\WebHookRepository;

class WebHooksController extends Controller
{
    /**
     * @var WebHookRepository
     */
    private $webHookRepository;

    public function __construct(WebHookRepository $webHookRepository)
    {
        $this->webHookRepository = $webHookRepository;
        // $this->middleware('logging');
    }

    public function index()
    {
        // 请求参数
        $project_name = request()->input('project');
        $token        = request()->input('token');
        if (empty($project_name) || empty($token)) {
            return $this->error(1000, '请求参数为空');
        }

        // 查询项目是否存在
        if (!$project = $this->webHookRepository->findOne(['name' => $project_name, 'status' => 1])) {
            return $this->error(1001, '项目不存在');
        }

        // 验证密码
        if ($project['token'] != $token) {
            return $this->error(1002, 'token 错误');
        }

        // 请求信息
        $body = file_get_contents('php://input');

        if ($project['type'] == 2) {
            // github 验证请求参数
            $sign = 'sha1=' . hash_hmac('sha1', $body, $project['password']);
            if ($sign !== $_SERVER['HTTP_X_HUB_SIGNATURE']) {
                return $this->error(1003, '密码错误');
            }
        } else {
            // gitee 验证请求参数
            $params = json_decode($body, true);
            if (empty($params) || array_get($params, 'password') !== array_get($project, 'password')) {
                return $this->error(1003, '密码错误');
            }
        }

        // 验证允许IP
        if (!$this->isAllowIp($project['allow_ips'])) {
            return $this->error(1004, '非法的请求,不允许的IP');
        }

        $command = $project['command'] ?: 'cd /www/html/' . $project_name . ' && git pull';
        exec($command);

        return $this->success([
            'ip'   => get_ip(),
            'time' => date('Y-m-d H:i:s'),
            'name' => $project_name,
            'desc' => $project['description']
        ]);
    }

    /**
     * 验证IP是允许
     *
     * @param string $allow_ips 允许的ip
     *
     * @return bool
     */
    private function isAllowIp($allow_ips)
    {
        $allow_ips  = explode(',', $allow_ips);
        $request_ip = get_ip();

        foreach ($allow_ips as $ip) {
            // 第一步： 全匹配
            if ($request_ip === $ip) {
                return true;
            }

            // 第二步：模糊匹配 前缀 * 替换为空
            if (starts_with($request_ip, str_replace_last('*', '', $ip))) {
                return true;
            }
        }

        return false;
    }
}